/*
 * UART.c
 *
 *  Created on: 29/12/2012
 *      Author: Bowmer
 */

#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_types.h"
#include "inc/tm4c123gh6pge.h"
#include "driverlib/gpio.h"



extern volatile unsigned int RxBufferIndex;
extern volatile unsigned char RxBuffer[200];


/* Transmit a string across UART4 */
void UART4_Send(char *pucBuffer, unsigned long TxCount){

	// Send specified number of characters
	while(TxCount--)
	{
		// Put the character into the FIFO, increase the index
		UART4_DR_R = *pucBuffer++;

		//Probably not using the FIFO to its full extent here. This isn't letting it fill up
		while(UART4_FR_R & UART_FR_BUSY);
	}
}

void UART4_Buffer_Init(){
	// Clear the receive buffer...
	for(RxBufferIndex = 0; RxBufferIndex<sizeof(RxBuffer); RxBufferIndex++){
		RxBuffer[RxBufferIndex]=0;
	}
	// ...and reset the index
	RxBufferIndex=0;

}



void UART4_Init(){

	// Enable PORTC peripheral
	SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R2;						//Add PORTC to enabled peripherals
	// Enable UART4 Peripheral
	SYSCTL_RCGCUART_R |= SYSCTL_RCGCUART_R4;

	// Configure PORTC
	GPIO_PORTC_DIR_R = (GPIO_PORTC_DIR_R & ~GPIO_PIN_4)|GPIO_PIN_5;	//Pin 4 is an input, 5 is an output. Maintain other bits
	GPIO_PORTC_AFSEL_R |= (GPIO_PIN_4|GPIO_PIN_5);					//Alternate function on pins 4,5
	GPIO_PORTC_PCTL_R |= GPIO_PCTL_PC4_U4RX|GPIO_PCTL_PC5_U4TX;		//Alternate function is UART4
	GPIO_PORTC_DEN_R |= GPIO_PIN_4|GPIO_PIN_5;						//Digital Enable pins 4,5



	// Configure UART4
	UART4_CTL_R &= ~0x01;											//Disable UART4
	UART4_IBRD_R = 260;												//Integer part of scaler
	UART4_FBRD_R = 27;												//Divisor part of scaler
	UART4_LCRH_R = 0x0070;											//8N1, Enable FIFO	//This NEEDS to follow the IBRD and FBRD writes
	UART4_CTL_R = 0x0310;											//Enable both transmit and receive
	//UART4_CTL_R |= 0x80;											//Enable Loopback
	UART4_CC_R = 0x00;												//Use PLL
	UART4_CTL_R |= 0x01;											//Enable UART4


	// Initialisation Strings
//	char beginString[]= "\033[2JStellaris Prime Standing by:\0";
//	char beginString2[]= " Ready To Receive:\0";

	// Send first initialisation string
//	UART4_Send(beginString, 31);

	// Enable UART4 Interrupts in the NVIC
	NVIC_EN1_R |= NVIC_EN0_INT28;

	// Enable Receive interrupts, and Receive Timeout interrupts
	UART4_IM_R = UART_IM_RXIM ;//| UART_IM_RTIM;

	// Send second initialisation string
//	UART4_Send(beginString2, 19);
}
